package com.maychat.websocket.netty;

import com.maychat.config.AppConfig;
import com.maychat.config.Consts;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class NettyWebSocketStarter implements Runnable {
    private static final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup();


    @Autowired
    private WebSocketHandler webSocketHandler;

    @Autowired
    private AppConfig appConfig;

    @PreDestroy
    public void close() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    @Override
    public void run() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new ChannelInitializer<>() {
                    @Override
                    protected void initChannel(Channel channel) {
                        ChannelPipeline pipeline = channel.pipeline();
                        // 支持http编解码
                        pipeline.addLast(new HttpServerCodec())
                                // 聚合解码
                                .addLast(new HttpObjectAggregator(64 * 1024))
                                // 心跳，(读超时，写超时，所有类型的超时时间)
                                .addLast(new IdleStateHandler(Consts.TIME_1MIN, 0, 0, TimeUnit.SECONDS))
                                // 自定义心跳处理器
                                .addLast(new HeartBeatHandler())
                                .addLast(new WebSocketServerProtocolHandler("/ws", null, true, 64 * 1024, true, true, 10000L))
                                .addLast(webSocketHandler);
                    }
                });
        Integer wsPort = appConfig.getWebsocketPort();
        String wsPortStr = System.getProperty("ws.port");
        if (wsPortStr != null) wsPort = Integer.parseInt(wsPortStr);
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(wsPort).sync();
            log.info("netty server started successfully");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("netty server started failed", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
